package com.fulu.game.bi.service.impl.export;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.fulu.game.bi.common.util.lang.GenIdUtil;
import com.fulu.game.bi.entity.ExportBO;
import com.fulu.game.bi.entity.bo.channel.DictItemBO;
import com.fulu.game.bi.entity.dto.ExportDTO;
import com.fulu.game.bi.entity.po.DictItem;
import com.fulu.game.bi.hive.HivePlayeeExportDao;
import com.fulu.game.bi.mysql.bi.DictItemDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

import static com.fulu.game.bi.common.util.OssUtil.EXPORT;

@Service
@Slf4j
public class ConsoleExportService {
    @Autowired
    private HivePlayeeExportDao hivePlayeeExportDao;
    @Autowired
    private DictItemDao dictItemDao;

    private static final String SUFFIX = ".csv";

    private static final String COLUMN_MAPPING = "COLUMN_MAPPING";

    public void export(ExportDTO dto) {
        StringBuilder sb = new StringBuilder();
        String uuid = GenIdUtil.GetGUID();
        sb.append(EXPORT)
                .append(DateUtil.thisYear())
                .append("/").append(DateUtil.thisMonth() + 1)
                .append("/").append(DateUtil.thisDayOfMonth())
                .append("/").append(dto.getFileName() + uuid).append(SUFFIX);
        ExportBO exportBO = new ExportBO();
        BeanUtils.copyProperties(dto, exportBO);
        exportBO.setKey(sb.toString());
        DictItemBO dictItemBO = new DictItemBO();
        dictItemBO.setDictCode(COLUMN_MAPPING);
        dictItemBO.setCode(dto.getTableName());
        List<DictItem> list = dictItemDao.findByParameter(dictItemBO);
        if (CollectionUtils.isEmpty(list)) {
            log.error("表结构配置，table:{}", dto.getTableName());
            return;
        }
        Map<String, String> maps = (Map) JSON.parse(list.get(0).getVal());
        exportBO.setColumnMap(maps);
        hivePlayeeExportDao.eventCondition(exportBO);
    }
}
